package com.itelite.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itelite.aop.WinControllerPointCut;
import com.itelite.common.info.Result;
import com.itelite.common.util.DateUtils;
import com.itelite.common.util.FileUtils;
import com.itelite.common.util.SecurityUtils;
import com.itelite.common.util.WordUtils;
import com.itelite.config.WebAppConfig;
import com.itelite.domain.dto.*;
import com.itelite.domain.pojo.Group;
import com.itelite.domain.pojo.TrainingRecord;
import com.itelite.handler.ValidateHandler;
import com.itelite.service.GroupService;
import com.itelite.service.RecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/8/6-8:33
 **/
@Api("培训记录模块")
@RequestMapping("/record/api")
@RestController
@Slf4j
public class RecordController {
    @Autowired
    private RecordService recordService;
    @Autowired
    private GroupService groupService;
    @PreAuthorize("hasAnyRole('ADMIN','USER')")
    @ApiOperation("上传培训记录")
    @PostMapping("/uploadTrainingRecord")
    @WinControllerPointCut
    public Result uploadTrainingRecord(@Validated TrainingRecord record, MultipartFile[] files, BindingResult error){
        if (error.hasErrors()) return Result.failure(ValidateHandler.catchErrors(error));
        //验证上传的文件只能是图片格式
        //image/jpeg image/png
        boolean isLegal = FileUtils.validateFilesExtensionNameForImage(files);
        if (!isLegal){
            return Result.failure("仅支持上传JPG、PNG图片");
        }
        boolean success = recordService.uploadTrainingRecord(record,files);
        if (success) return Result.success("上传成功!");
        else return Result.failure("上传失败请联系管理员");
    }
    @ApiOperation("获取培训记录详情")
    @GetMapping("/trainingRecordDetail/{recordId}")
    public Result getTrainingRecordDetail(@PathVariable Integer recordId){
        TrainingRecordDto record = recordService.getTrainingRecordDetail(recordId);
        return Result.success().build().data("record",record);
    }

    @ApiOperation("获取培训记录列表")
    @PostMapping("/recordList")
    public Result getRecordList(@RequestBody@Validated RecordParam param){
        PageInfo<TrainingRecordVo> recordVoList = recordService.getTrainingRecordList(param);
        if (recordVoList==null)return Result.failure("GroupIds参数错误");
        return Result.success().build().data("recordList",recordVoList);
    }

    @PreAuthorize("hasAnyRole('ADMIN','USER')")
    @ApiOperation("删除培训记录")
    @GetMapping("/deleteRecord/{recordId}")
    @WinControllerPointCut
    public Result deleteRecord(@PathVariable Integer recordId){
        Integer belongingGroupId = recordService.getRecordBelongingGroupId(recordId);
        if(belongingGroupId==null){
            return Result.failure("错误编号");
        }
        List<Group> groups = groupService.getUserControlGroupList();
        AtomicBoolean isDelete = new AtomicBoolean(false);
        groups.forEach(g->{
            if(g.getGroupId().equals(belongingGroupId)) isDelete.set(true);
        });
        Result result = null;
        if (isDelete.get()){
            if (recordService.deleteRecord(recordId)) {
                log.info("删除记录的编号(RecordID): {}",recordId);
                result=Result.success("操作成功");
            }else result = Result.failure("操作失败请重试");
        }else {
            result=Result.success("权限不足");
        }
        return result;
    }
    @ApiOperation("获取时间线培训记录")
    @PostMapping("/timelineRecord")
    public Result getTimelineRecord(@RequestBody @Validated BaseParam param){
        PageInfo<TimelineRecord> recordVoList = recordService.getTimelineRecord(param);
        return Result.success().build().data("recordList",recordVoList);
    }

    @ApiOperation("获取学期信息")
    @GetMapping("/term")
    public Result getTerms() throws ParseException {
        return Result.success().build().data("terms", DateUtils.getTerms());
    }
    @ApiOperation("导出WORD培训记录")
    @WinControllerPointCut
    @GetMapping("/exportWordRecord/{recordId}")
    public void downloadRecord(@PathVariable Integer recordId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String,Object> params = recordService.getWordRecordParam(recordId);
        if(params==null){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(Result.failure("无记录")));
            return;
        }
        //这里是我说的一行代码
        Integer s = (Integer) params.get("size");
        String wordPath = null;
        if(s==1){
            wordPath=WebAppConfig.IT_Record_WORD_1;
        }else if(s==2){
            wordPath=WebAppConfig.IT_Record_WORD_2;
        }else if(s==3){
            wordPath=WebAppConfig.IT_Record_WORD_3;
        }else if(s==4){
            wordPath=WebAppConfig.IT_Record_WORD_4;
        }else if(s==5){
            wordPath=WebAppConfig.IT_Record_WORD_5;
        }else{
            wordPath=WebAppConfig.IT_Record_WORD_6;
        }
        WordUtils.exportWordByImg(WebAppConfig.ROOT+ File.separator+
                WebAppConfig.ROOT_DIR_CONFIG+File.separator+wordPath,"培训记录.docx",params,request,response);
    }
}
